package server

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"stargazer/xnat/xnetc/client"
	"sync"
)

type Mux struct {
	connMap map[string]*net.Conn
}

var (
	mux  *Mux
	lock = &sync.Mutex{}
)

func GetMuxInstance() *Mux {
	lock.Lock()
	defer lock.Unlock()
	if mux == nil {
		mux = &Mux{}
		mux.connMap = make(map[string]*net.Conn)
	}
	return mux
}

func readFromTCPConn(conn *net.Conn) (buf []byte) {
	len := 0
	buf = make([]byte, 2048)
	var data []byte
	for {
		n, err := (*conn).Read(buf)
		if n > 0 {
			len += n
			for i := 0; i < n; i++ {
				data = append(data, buf[i])
			}
		}
		if err != nil {
			if err != io.EOF {
				log.Println(err.Error())
			}
			break
		}
		if n < 2048 {
			break
		}
	}
	return data
}

// 交互http数据
func (mux *Mux) exchangeHTTPMsg(reqData client.HttpRequestData, username string, ch chan client.HttpResponseData) {
	// 向远程客户端写requestData对象
	// httpBuf := new(bytes.Buffer)
	// err := binary.Write(httpBuf, binary.LittleEndian, reqData)
	// if err != nil {
	// 	log.Fatal(err.Error())
	// }
	httpBuf, err := json.Marshal(reqData)
	if err != nil {
		// fmt.Println(string(httpBuf[:l]))
		log.Fatal(err.Error())
	}

	conn, exist := mux.connMap[username]
	if !exist {
		fmt.Println("user is not activated")
		return
	}
	(*conn).Write(httpBuf)

	// 读取返回的response对象
	// tcpBuf := make([]byte, 4096)
	// l, _ := (*conn).Read(tcpBuf)
	// repBuffer := bytes.NewBuffer(tcpBuf[:l])
	var responseData client.HttpResponseData
	resBuf := readFromTCPConn(conn)

	// err = binary.Read(repBuffer, binary.LittleEndian, &response)
	// err = json.Unmarshal(tcpBuf[:l], &responseData)
	err = json.Unmarshal(resBuf, &responseData)
	if err != nil {
		log.Println("binary.Write failed:", err)
	}
	ch <- responseData
}

func (mux *Mux) AcceptFromTCPServer(s *TCPServer) {
	for {
		conn := <-(*s).ConnChan
		isOk, username := AuthencatieUser(conn)
		if !isOk {
			return
		}
		mux.connMap[username] = conn
	}
}
